// ImageSprite.cpp
#include "ImageSprite.h"

namespace ANvDbg
{
    ImageSprite::ImageSprite() : m_texture(nullptr), m_alpha(1.f), m_is_fade_in_animation(false)
    {

    }

    void ImageSprite::Init(float x, float y, float width, float height)
    {
        float half_width = width / 2.f;
        float half_height = height / 2.f;

        m_vertex[0] = x - half_width;
        m_vertex[1] = y - half_height;
        m_vertex[2] = -1.f;

        m_vertex[3] = x + half_width;
        m_vertex[4] = y - half_height;
        m_vertex[5] = -1.f;

        m_vertex[6] = x + half_width;
        m_vertex[7] = y + half_height;
        m_vertex[8] = -1.f;

        m_vertex[9] = x - half_width;
        m_vertex[10] = y + half_height;
        m_vertex[11] = -1.f;

        if (m_next != nullptr)
        {
            GetNext<ImageSprite>()->Render();
        }
    }

    void ImageSprite::Render()
    {
        if (m_is_fade_in_animation)
        {
            FadingIn();
        }

        glDisable(GL_LIGHTING);
        glEnable(GL_TEXTURE_2D);
        glEnable(GL_BLEND);
        glDisable(GL_DEPTH_TEST);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        glBindTexture(GL_TEXTURE_2D, m_texture->m_texture_id);
        glColor4f(1.f, 1.f, 1.f, m_alpha);
        glBegin(GL_QUADS);
        glTexCoord2f(0, 0); glVertex3fv(m_vertex);
        glTexCoord2f(1, 0); glVertex3fv(m_vertex + 3);
        glTexCoord2f(1, 1); glVertex3fv(m_vertex + 6);
        glTexCoord2f(0, 1); glVertex3fv(m_vertex + 9);
        glEnd();
    }

    void ImageSprite::FadeIn(float duration)
    {
        m_fade_in_duration = duration;
        m_is_fade_in_animation = true;
        m_alpha = 1.f;
    }

    void ImageSprite::FadingIn()
    {
        m_alpha -= 0.1f;
        if (m_alpha < 0.f)
        {
            m_is_fade_in_animation = false;
            m_alpha = 1.f;
        }
    }
}
